<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>花间村 - 微信服务号</title>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <style>
        /* 基础样式 */
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f8f9fa;
            color: #333;
            padding-bottom: 60px;
            -webkit-tap-highlight-color: transparent;
        }

        .container {
            max-width: 100%;
            padding: 10px;
        }

        /* 顶部搜索栏 */
        .search-bar {
            position: sticky;
            top: 0;
            background: white;
            padding: 10px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            z-index: 100;
            display: flex;
            margin-bottom: 10px;
            border-radius: 8px;
        }

        .search-input {
            flex: 1;
            padding: 8px 15px;
            border: 1px solid #ddd;
            border-radius: 20px;
            font-size: 14px;
        }

        /* 商品卡片优化 */
        .product-card {
            background: #fff;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            transition: transform 0.2s, box-shadow 0.2s;
            position: relative;
            overflow: hidden;
        }

        .product-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .product-image {
            width: 100%;
            height: 180px;
            object-fit: cover;
            border-radius: 8px;
            margin-bottom: 10px;
            background-color: #f5f5f5;
            transition: opacity 0.3s;
        }

        .product-image.loading {
            opacity: 0.5;
        }

        .product-title {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 8px;
            color: #333;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            height: 44px;
            line-height: 1.4;
        }

        .product-price {
            font-size: 18px;
            color: #e63946;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .stock-info {
            font-size: 13px;
            margin-bottom: 8px;
            color: #666;
        }

        .stock-info.low-stock {
            color: #e74c3c;
            font-weight: 500;
        }

        .stock-info.out-of-stock {
            color: #e74c3c;
            font-weight: bold;
        }

        .quantity-control {
            display: flex;
            align-items: center;
            margin-bottom: 12px;
            justify-content: space-between;
            background: #f8f9fa;
            padding: 8px;
            border-radius: 6px;
        }

        .quantity-buttons {
            display: flex;
            align-items: center;
        }

        .quantity-btn {
            width: 28px;
            height: 28px;
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 16px;
            transition: all 0.2s;
        }

        .quantity-btn:active {
            background: #e9ecef;
            transform: scale(0.95);
        }

        .quantity-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .quantity-input {
            width: 40px;
            text-align: center;
            margin: 0 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 4px;
            font-size: 14px;
        }

        .add-to-cart-btn {
            background-color: #07C160;
            color: white;
            border: none;
            border-radius: 20px;
            padding: 10px 15px;
            font-size: 14px;
            cursor: pointer;
            display: inline-block;
            transition: background-color 0.2s, transform 0.2s;
            font-weight: 500;
            width: 100%;
            box-sizing: border-box;
            text-align: center;
        }

        .add-to-cart-btn:disabled {
            background-color: #95a5a6;
            cursor: not-allowed;
        }

        .add-to-cart-btn:not(:disabled):hover {
            background-color: #05a854;
            transform: translateY(-2px);
        }

        .add-to-cart-btn:active {
            transform: translateY(0);
        }

        /* 底部导航栏 */
        .bottom-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            height: 60px;
            background: #fff;
            display: flex;
            justify-content: space-around;
            align-items: center;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
            z-index: 200;
            padding: 0 5px;
        }

        .nav-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            color: #7f8c8d;
            font-size: 12px;
            padding: 8px 12px;
            border-radius: 8px;
            transition: all 0.2s;
        }

        .nav-item.active {
            color: #07C160;
            background: rgba(7, 193, 96, 0.1);
        }

        .nav-icon {
            font-size: 20px;
            margin-bottom: 3px;
        }

        .cart-badge {
            position: absolute;
            top: 0;
            right: 0;
            background: #e74c3c;
            color: white;
            border-radius: 50%;
            width: 18px;
            height: 18px;
            font-size: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }

        /* 加载指示器 */
        .loader {
            text-align: center;
            padding: 20px;
            font-size: 14px;
            color: #7f8c8d;
        }

        .loader-dots {
            display: inline-block;
            position: relative;
            width: 80px;
            height: 20px;
        }

        .loader-dots div {
            position: absolute;
            top: 0;
            width: 13px;
            height: 13px;
            border-radius: 50%;
            background: #07C160;
            animation-timing-function: cubic-bezier(0, 1, 1, 0);
        }

        .loader-dots div:nth-child(1) {
            left: 8px;
            animation: loader-dots1 0.6s infinite;
        }

        .loader-dots div:nth-child(2) {
            left: 8px;
            animation: loader-dots2 0.6s infinite;
        }

        .loader-dots div:nth-child(3) {
            left: 32px;
            animation: loader-dots2 0.6s infinite;
        }

        .loader-dots div:nth-child(4) {
            left: 56px;
            animation: loader-dots3 0.6s infinite;
        }

        @keyframes loader-dots1 {
            0% {
                transform: scale(0);
            }

            100% {
                transform: scale(1);
            }
        }

        @keyframes loader-dots3 {
            0% {
                transform: scale(1);
            }

            100% {
                transform: scale(0);
            }
        }

        @keyframes loader-dots2 {
            0% {
                transform: translate(0, 0);
            }

            100% {
                transform: translate(24px, 0);
            }
        }

        /* 通知提示 */
        .notification {
            position: fixed;
            bottom: 70px;
            left: 50%;
            transform: translateX(-50%);
            background: #07C160;
            color: white;
            padding: 12px 24px;
            border-radius: 30px;
            z-index: 300;
            box-shadow: 0 4px 12px rgba(7, 193, 96, 0.3);
            animation: slideIn 0.3s ease-out;
            font-weight: 500;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translate(-50%, 20px);
            }

            to {
                opacity: 1;
                transform: translate(-50%, 0);
            }
        }
    </style>
</head>

<body>
    <!-- 顶部搜索栏 -->
    <div class="search-bar">
        <input type="text" class="search-input" placeholder="搜索商品...">
    </div>

    <div class="container">
        <!-- 首页横幅图片 -->
        <div style="margin-bottom: 15px; border-radius: 12px; overflow: hidden;">
            <img 
                src="{{ asset('images/Membership Reminder.jpg') }}" 
                alt="花间村" 
                style="width: 100%; height: auto; display: block;"
                loading="lazy"
            >
        </div>
        
        @foreach($products as $product)
        <div class="product-card" data-id="{{ $product->id }}" data-stock="{{ $product->stock }}">
            <!-- 商品图片和名称 -->
            <a href="{{ route('wechat.service.account.product.show', $product->id) }}" style="text-decoration: none; color: inherit;">
                @php
                $images = $product->images ?? [];
                $firstImage = count($images) > 0 ? $images[0] : ($product->media->first() ? $product->media->first()->getUrl() : $product->image_url);
                @endphp
                <img
                    src="{{ $firstImage }}"
                    class="product-image"
                    alt="{{ $product->name }}"
                    loading="lazy"
                    onerror="this.src='{{ asset('images/default_product.jpg') }}'">
                <div class="product-title">{{ $product->name }}</div>
            </a>

            <div class="product-price">¥{{ number_format($product->price, 2) }}</div>

            <!-- 库存状态 -->
            <div class="stock-info {{ $product->stock <= 0 ? 'out-of-stock' : ($product->stock <= 10 ? 'low-stock' : '') }}">
                {{ $product->stock <= 0 ? '已售罄' : '库存: '.$product->stock.($product->stock <= 10 ? '（库存紧张）' : '') }}
            </div>

            <!-- 数量选择 -->
            <div class="quantity-control">
                <span>数量</span>
                <div class="quantity-buttons">
                    <button class="quantity-btn decrease-btn">-</button>
                    <input type="number" class="quantity-input" value="1" min="1" max="{{ $product->stock }}">
                    <button class="quantity-btn increase-btn">+</button>
                </div>
            </div>

            <!-- 操作按钮区域 -->
            <div style="display: flex; gap: 10px;">
                <!-- 加入购物车按钮 -->
                <button
                    class="add-to-cart-btn"
                    style="flex: 1;"
                    data-product-id="{{ $product->id }}"
                    {{ $product->stock <= 0 ? 'disabled' : '' }}>
                    {{ $product->stock <= 0 ? '已售罄' : '加入购物车' }}
                </button>
                
                <!-- 购买按钮 -->
                <button
                    class="buy-now-btn"
                    style="flex: 1; background-color: #e63946; color: white; border: none; padding: 10px; border-radius: 5px; cursor: pointer;"
                    data-product-id="{{ $product->id }}"
                    {{ $product->stock <= 0 ? 'disabled' : '' }}>
                    {{ $product->stock <= 0 ? '已售罄' : '购买' }}
                </button>
            </div>
        </div>
        @endforeach

        <!-- 加载指示器 -->
        <!-- <div class="loader">
            <div class="loader-dots">
                <div></div>
                <div></div>
                <div></div>
                <div></div>
            </div>
            <div id="loading-more" style="text-align: center; padding: 15px; display: none;">
                正在加载更多商品...
            </div>

        </div> -->




    </div>

    <!-- 底部导航栏 -->
    <div class="bottom-nav">
        <div class="nav-item active" data-route="{{ route('wechat.service.account.index') }}">
            <span class="nav-icon">🏠</span>
            <span>首页</span>
        </div>
        <div class="nav-item" data-route="{{ route('wechat.service.account.cart') }}">
            <span class="nav-icon">🛒</span>
            <span>购物车</span>
            @php
                $cartCount = app(\App\Services\CartService::class)->getCartCount();
            @endphp
            @if($cartCount > 0)
                <span class="cart-badge">{{ $cartCount }}</span>
            @endif
        </div>
        <div class="nav-item" data-route="{{ route('wechat.service.account.my') }}">
            <span class="nav-icon">👤</span>
            <span>我的</span>
        </div>
    </div>

    <script>
        // 预定义路由和令牌，避免在JavaScript中直接使用Blade语法
        const addToCartUrl = "{{ route('wechat.service.account.cart.add') }}";
        const checkoutUrl = "{{ route('wechat.service.account.checkout') }}";
        const csrfToken = "{{ csrf_token() }}";
        
        // 立即购买功能
        function buyNow(productId) {
            // 获取当前商品对应的数量输入框和按钮
            const productCard = document.querySelector(`.product-card[data-id="${productId}"]`);
            const quantityInput = productCard.querySelector('.quantity-input');
            const buyButton = document.querySelector(`.buy-now-btn[data-product-id="${productId}"]`);
            
            // 禁用按钮防止重复点击
            buyButton.disabled = true;
            buyButton.textContent = '添加中...';
            
            // 获取并验证数量
            let quantity = parseInt(quantityInput.value) || 1;
            
            // 验证库存
            const stock = parseInt(productCard.getAttribute('data-stock'));
            if (quantity > stock) {
                alert('购买数量超过库存');
                quantityInput.value = stock;
                buyButton.disabled = false;
                buyButton.textContent = '购买';
                return;
            }
            
            // 确保数量有效
            quantity = Math.min(Math.max(quantity, 1), stock);
            
            // 先将商品添加到购物车
            axios.post(addToCartUrl, {
                product_id: productId,
                quantity: quantity
            }, {
                headers: {
                    'X-CSRF-TOKEN': csrfToken,
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                if (response.data.success) {
                    // 更新购物车红点
                    updateCartBadge(response.data.total_quantity);
                    
                    // 显示成功通知
                    showNotification('✓ 已添加到购物车');
                    
                    // 短暂延迟后跳转到购物车页面
                    setTimeout(() => {
                        window.location.href = "{{ route('wechat.service.account.cart') }}";
                    }, 1000);
                } else {
                    showNotification('添加失败: ' + response.data.message);
                    buyButton.disabled = false;
                    buyButton.textContent = '购买';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                
                // 检查是否是401未授权错误（用户未登录）
                if (error.response && error.response.status === 401) {
                    showNotification('请先登录后再添加商品');
                    // 跳转到登录页面
                    setTimeout(() => {
                        window.location.href = "{{ route('wechat.service.account.login') }}";
                    }, 1500);
                } else {
                    showNotification('网络异常，请重试');
                }
                
                buyButton.disabled = false;
                buyButton.textContent = '购买';
            });
        }
        
        // 为所有购买按钮添加点击事件
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.buy-now-btn').forEach(button => {
                button.addEventListener('click', function() {
                    if (this.disabled) return;
                    const productId = this.getAttribute('data-product-id');
                    
                    // 调用购买函数
                    buyNow(productId);
                });
            });
        });
        
        // 购买按钮样式优化
        const style = document.createElement('style');
        style.textContent = `
            .buy-now-btn {
                background-color: #e63946;
                color: white;
                border: none;
                border-radius: 20px;
                padding: 10px 15px;
                font-size: 14px;
                cursor: pointer;
                display: inline-block;
                transition: background-color 0.2s, transform 0.2s;
                font-weight: 500;
                flex: 1;
                box-sizing: border-box;
                text-align: center;
            }
            
            .buy-now-btn:disabled {
                background-color: #95a5a6;
                cursor: not-allowed;
            }
            
            .buy-now-btn:not(:disabled):hover {
                background-color: #c1121f;
                transform: translateY(-2px);
            }
            
            .buy-now-btn:active {
                transform: translateY(0);
            }
        `;
        document.head.appendChild(style);
        
        // 微信分享配置
        wx.config({
            debug: false,
            appId: '{{ $wxConfig["appId"] }}',
            timestamp: '{{ $wxConfig["timestamp"] }}',
            nonceStr: '{{ $wxConfig["nonceStr"] }}',
            signature: '{{ $wxConfig["signature"] }}',
            jsApiList: [
                'updateAppMessageShareData',
                'updateTimelineShareData'
            ]
        });

        wx.ready(function() {
            // 自定义分享内容
            wx.updateAppMessageShareData({
                title: '花间村 - 发现好物',
                desc: '精选{{ count($products) }}款优质商品，限时优惠中',
                link: window.location.href,
                imgUrl: '{{ asset("images/share_logo.png") }}',
                success: function() {}
            });

            wx.updateTimelineShareData({
                title: '花间村 - 发现好物',
                link: window.location.href,
                imgUrl: '{{ asset("images/share_logo.png") }}',
                success: function() {}
            });
        });

        // 图片懒加载
        document.addEventListener('DOMContentLoaded', function() {
            const lazyImages = document.querySelectorAll('.product-image');
            const observer = new IntersectionObserver((entries, observer) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const img = entry.target;
                        img.src = img.dataset.src || img.src;
                        img.classList.remove('loading');
                        observer.unobserve(img);
                    }
                });
            }, {
                rootMargin: '0px 0px 100px 0px'
            });

            lazyImages.forEach(img => {
                img.classList.add('loading');
                observer.observe(img);
            });
        });

        // 事件委托处理数量增减
        document.querySelector('.container').addEventListener('click', function(e) {
            const target = e.target;

            // 处理减少按钮
            if (target.classList.contains('decrease-btn')) {
                const input = target.closest('.quantity-buttons').querySelector('.quantity-input');
                let value = parseInt(input.value) || 1;
                if (value > 1) {
                    input.value = value - 1;
                }
            }

            // 处理增加按钮
            if (target.classList.contains('increase-btn')) {
                const input = target.closest('.quantity-buttons').querySelector('.quantity-input');
                const productCard = target.closest('.product-card');
                const maxStock = parseInt(productCard.dataset.stock);

                let value = parseInt(input.value) || 1;
                if (value < maxStock) {
                    input.value = value + 1;
                }
            }
        });

        // 输入框直接输入的处理
        document.querySelectorAll('.quantity-input').forEach(input => {
            input.addEventListener('change', function() {
                const maxStock = parseInt(this.closest('.product-card').dataset.stock);
                let value = parseInt(this.value) || 1;

                if (value < 1) value = 1;
                if (value > maxStock) value = maxStock;

                this.value = value;
            });
        });

        // 加入购物车逻辑
        document.querySelectorAll('.add-to-cart-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                if (this.disabled) return;

                const productCard = this.closest('.product-card');
                const productId = this.dataset.productId;
                const quantity = parseInt(productCard.querySelector('.quantity-input').value);
                const maxStock = parseInt(productCard.dataset.stock);

                // 最终确认数量不超过库存
                const finalQuantity = Math.min(quantity, maxStock);

                // 禁用按钮防止重复点击
                const originalText = this.textContent;
                this.textContent = '添加中...';
                this.disabled = true;

                // 发送请求
                axios.post('{{ route("wechat.service.account.cart.add") }}', {
                        product_id: productId,
                        quantity: finalQuantity
                    }, {
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                            'Content-Type': 'application/json'
                        }
                    })
                    .then(response => {
                        if (response.data.success) {
                            // 更新购物车红点
                            updateCartBadge(response.data.total_quantity);

                            // 显示成功通知
                            showNotification('✓ 已添加到购物车');

                            // 短暂改变按钮状态
                            this.textContent = '✓ 已添加';
                            setTimeout(() => {
                                this.textContent = originalText;
                                this.disabled = false;
                            }, 2000);
                        } else {
                            showNotification('添加失败: ' + response.data.message);
                            this.textContent = originalText;
                            this.disabled = false;
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        
                        // 检查是否是401未授权错误（用户未登录）
                        if (error.response && error.response.status === 401) {
                            showNotification('请先登录后再添加商品');
                            // 跳转到登录页面
                            setTimeout(() => {
                                window.location.href = '{{ route("wechat.service.account.login") }}';
                            }, 1500);
                        } else {
                            showNotification('网络异常，请重试');
                        }
                        
                        this.textContent = originalText;
                        this.disabled = false;
                    });
            });
        });

        // 更新购物车红点
        function updateCartBadge(quantity) {
            const cartBadge = document.querySelector('.cart-badge');
            if (cartBadge) {
                cartBadge.textContent = quantity > 99 ? '99+' : quantity;
                cartBadge.style.display = quantity > 0 ? 'flex' : 'none';
            }
        }

        // 显示通知
        function showNotification(message) {
            // 移除现有通知
            const existing = document.querySelector('.notification');
            if (existing) existing.remove();

            // 创建新通知
            const notification = document.createElement('div');
            notification.className = 'notification';
            notification.textContent = message;
            document.body.appendChild(notification);

            // 3秒后移除通知
            setTimeout(() => {
                notification.style.opacity = '0';
                setTimeout(() => {
                    notification.remove();
                }, 300);
            }, 2000);
        }

        // 滚动加载更多（示例）
        window.addEventListener('scroll', function() {
            const {
                scrollTop,
                scrollHeight,
                clientHeight
            } = document.documentElement;
            if (scrollTop + clientHeight >= scrollHeight - 200) {
                // 模拟加载更多
                const loader = document.querySelector('.loader');
                if (loader) loader.style.display = 'block';

                setTimeout(() => {
                    if (loader) loader.style.display = 'none';
                }, 1000);
            }
        });

        // 底部导航栏点击事件
        document.addEventListener('DOMContentLoaded', function() {
            const navItems = document.querySelectorAll('.nav-item');
            
            navItems.forEach(item => {
                item.addEventListener('click', function() {
                    const route = this.getAttribute('data-route');
                    if (route) {
                        // 移除所有active类
                        navItems.forEach(nav => nav.classList.remove('active'));
                        // 添加active类到当前点击的项目
                        this.classList.add('active');
                        // 跳转到对应页面
                        window.location.href = route;
                    }
                });
            });
        });

        // 加载开始时显示
        function showLoading() {
            document.getElementById('loading-more').style.display = 'block';
        }

        // 加载完成时隐藏
        function hideLoading() {
            document.getElementById('loading-more').style.display = 'none';
        }

        // 在AJAX请求中使用
        axios.get('/api/products')
            .then(function(response) {
                showLoading();
                // 处理数据...
            })
            .finally(function() {
                hideLoading();
            });
    </script>
    @include('wechat.service_account.components.bottom_nav')
</body>

</html>